﻿using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata.Ecma335;
using System.Text;
using System.Threading.Tasks;

namespace Lightworks.Core.Service
{
    public static class ServiceCollectionExtensions
    {
        public static IServiceCollection MapBusinessService(this IServiceCollection services,List<string>? scope)
        {
            /**
            List<Type> types = AppDomain.CurrentDomain.GetAssemblies()
                .Where(x=> scope.Contains(x.GetName().Name))
                .SelectMany(x => x.GetTypes())
                .Where(x => x.IsClass && !x.IsAbstract && x.GetCustomAttributes(typeof(ServiceAttribute), false).Length > 0)
                .ToList();
            
            **/
            List<Type> types = new List<Type>();
            scope!.ForEach(x=> {
                var a = Assembly.Load(x);
                var t = a.GetTypes().Where(x => x.IsClass && !x.IsAbstract && x.GetCustomAttributes(typeof(ServiceAttribute), false).Length > 0)
                .ToList();
                types.AddRange(t);
            });
            foreach (var type in types)
            {
                // 获取服务实现的所有接口
                Type[] interfaces = type.GetInterfaces();
                var lifetime = type.GetCustomAttribute<ServiceAttribute>()!.Lifetime;
                interfaces.ToList().ForEach(x =>
                {
                    switch (lifetime)
                    {
                        case ServiceLifetime.Singleton:
                            services.AddSingleton(x, type);
                            break;
                        case ServiceLifetime.Transient:
                            services.AddTransient(x, type);
                            break;
                        case ServiceLifetime.Scoped:
                            services.AddScoped(x, type);
                            break;
                    }
                });
            }
            return services;

        }
    }
}
